<template>
    <div>
        <div id="map" class="map"></div>
        <div class="btn">
            <el-button @click="openPoylineDraw" :disabled="compState.whetherOpenDisabled">开启线路绘制</el-button>
            <el-button @click="closePoylineDraw">关闭线路绘制</el-button>
            <el-button @click="openCurPoylineEdit" :disabled="compState.whetherDisabed">当前线路编辑</el-button>
            <!-- <el-button @click="clearCurPoylineDraw">清除当前线路</el-button> -->
            <!-- <el-button @click="clearAllLineDraw">清除所有线路</el-button> -->
            <el-button @click="handleCeDistance">开启测距</el-button>
        </div>
        <add-or-edit-poyline :dialogVisibleNum="compState.dialogVisibleNum" :operateType="compState.operateType"
            :allPoints="compState.allPoints" @closePoylineDrawEmit="closePoylineDraw"
            @clearCurPoylineDrawEmit="clearCurPoylineDraw" @showAddpoylineEmit="showAddpoyline"
            :poylineId="compState.poylineId"></add-or-edit-poyline>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import AddOrEditPoyline from './childComponent/AddOrEditPoyline.vue';
import {
    DrawScene,
    PolylineDraw,
    PolylineEdit,
    ActionStatus,
    OperateEventType,
    DistanceMeasure
} from 'bmap-draw';
import { onBeforeRouteLeave } from 'vue-router'
import { MarkLine } from '../../network/poyline'
onBeforeRouteLeave((to, from) => {
    sessionStorage.removeItem("poylineId")
})
var map = null
const compState = reactive({
    isOpen: false,
    polylineDraw: null,
    dialogVisibleNum: 1,
    scene: null,
    operateType: "",
    // 折线编辑
    sline: null,
    oldPayLine: null,
    curPoyline: null,
    allPoints: [],
    poylineId: 0,
    overlays: [],
    whetherDisabed: true,
    whetherOpenDisabled: false,
    // 测距离
    ceDistance: null
})

// 1.初始化地图方法
const InitMyMap = () => {
    // console.log(map)
    map = new BMapGL.Map('map'); // 创建地图实例
    map.centerAndZoom(new BMapGL.Point(120.214465, 30.254098), 12); // 初始化地图，设置中心点坐标和地图级别
    var myCity = new BMapGL.LocalCity();
    myCity.get((result) => {
        var cityName = result.name;
        map.setCenter(cityName);
    });
    map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

    // 添加鼠标绘制
    compState.scene = new DrawScene(map);
    compState.polylineDraw = new PolylineDraw(compState.scene, {
        isOpen: false,
        labelOptions: {
            borderRadius: '2px',
            background: '#fff',
            border: '1px solid #b5d3fb',
            color: '#333',
            fontSize: '12px',
            letterSpacing: '0',
            padding: '5px'
        },
        baseOpts: {
            strokeWeight: 4,
            strokeOpacity: 1,
            fillOpacity: 0.2
        },
        isSeries: true,
    });
    // 实例化线编辑
    compState.sline = new PolylineEdit(compState.scene);

    // 测距离
    compState.ceDistance = new DistanceMeasure(compState.scene, {
        isSeries: false // 不连续测量
    });
    compState.ceDistance.close()
};
// 开启绘制
const openPoylineDraw = () => {
    compState.polylineDraw.open()
}
// 关闭绘制
const closePoylineDraw = () => {
    // 关闭绘制
    compState.polylineDraw.close()
    if (compState.curPoyline != null) {
        // 不为空清除绘制的线路
        compState.scene.removeOverlay(compState.curPoyline);
    }
}
// 清除当前正在绘制的折线
const clearCurPoylineDraw = () => {
    if (compState.curPoyline != null) {
        compState.scene.removeOverlay(compState.curPoyline);
    }
    compState.curPoyline = null
}
// 清除所有的折线
const clearAllLineDraw = () => {
    compState.scene.clearData();
}
// 开启编辑
const openCurPoylineEdit = () => {
    if (compState.oldPayLine != null) {
        compState.sline.open(compState.oldPayLine)
    } else {
        console.log('compState.oldPayLine is null')
    }

}
const showAddpoyline = (val) => {
    // console.log(val)
    let points = []
    val?.pointsArr?.forEach(item => {
        let p = new BMapGL.Point(item.lng, item.lat)
        points.push(p)
    })
    let polyline = new BMapGL.Polyline(points,
        {
            strokeColor: val?.strokeColor,
            strokeWeight: val?.strokeWeight,
            strokeOpacity: val?.strokeOpacity,
            strokeStyle: val?.strokeStyle
        });
    // 显示添加成功的线路
    if (compState.oldPayLine != null) {
        map.removeOverlay(compState.oldPayLine)
    }
    map.addOverlay(polyline);
    compState.oldPayLine = polyline
    // 关闭正在绘制的线路
    clearCurPoylineDraw()
}
const handleCeDistance = () => {
    compState.ceDistance.open()
}
// 
onMounted(() => {
    // 初始化地图
    InitMyMap()
    // 监听绘制完成事件
    compState.scene.addEventListener(OperateEventType.COMPLETE, e => {
        let overlay = e.target.overlay
        compState.curPoyline = overlay
        // console.log(overlay)
        // console.log(overlay.getPath())
        switch (e.target.from) {
            case ActionStatus.DRAW_ON_MAP:
                console.log("新增")
                // 绘制图形存储与样式处理
                // 标识新增弹窗
                compState.operateType = "add"
                // 赋值 便于编辑
                // 保存到数组
                if (overlay != null) {
                    compState.allPoints = overlay.getPath()
                } else {
                    console.log('overlay is null')
                }
                // 打开新增弹窗
                compState.dialogVisibleNum++
                break;
            case ActionStatus.EDIT_ON_MAP:
                console.log("更新")
                if (overlay != null) {
                    compState.allPoints = overlay.getPath()
                } else {
                    console.log('overlay is null')
                }
                // 标识新增弹窗
                compState.operateType = "update"
                // 打开更新弹窗
                compState.dialogVisibleNum++
                break;
            case ActionStatus.SELECT_NO_MAP:
                break;
            case ActionStatus.SELECT_ON_MAP:
                break;
            default:
                break;
        }
    })
    // 监听绘制取消事件
    compState.scene.addEventListener(OperateEventType.CANCEL, e => {
        console.log("绘制取消了")
    })
    // 线编辑监听
    compState.sline.addEventListener('operate-change', e => {
        // 会多次触发
        // console.log('operate-change', e.target);
        compState.curPoyline = e.target
    });
    compState.sline.addEventListener('operate-ok', e => {
        // 编辑完成
        console.log('编辑完成')
    });
    compState.sline.addEventListener('operate-cancel', e => {
        // 编辑取消
        console.log('编辑取消')
    });

    // 如果是从线路列表跳进来，判断sessionStore中是否有线路Id
    compState.poylineId = sessionStorage.getItem("poylineId")
    if (compState.poylineId != undefined) {
        compState.whetherDisabed = false
        // compState.whetherOpenDisabled = true
        compState.poylineId = Number(compState.poylineId)
        // console.log(compState.poylineId)
        // 请求数据显示线路
        MarkLine({
            ID: compState.poylineId
        }).then(res => {
            // console.log(res)
            if (res && res?.length > 0) {
                res[0].Path = JSON.parse(res[0].Path)
                let points = []
                res[0]?.Path?.forEach(item => {
                    let p = new BMapGL.Point(item.lng, item.lat)
                    points.push(p)
                })
                let polyline = new BMapGL.Polyline(points,
                    {
                        strokeColor: res[0]?.Colour,
                        strokeWeight: res[0]?.Width,
                        strokeOpacity: res[0]?.Pellucidity,
                        strokeStyle: res[0]?.Pattern
                    });
                map.addOverlay(polyline);
                compState.oldPayLine = polyline
            }

        }).catch(err => {
            console.log(err)
        })
    }

    // 监听测量结果
    compState.ceDistance.addEventListener('measure-length-end', e => {
        console.log('measure-end', e);
    });
})
</script>

<style scoped>
.map {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 0;
}

.btn {
    position: absolute;
    left: 100px;
    bottom: 10px;
}
</style>